<template>
  <div class="main-context">
    <!-- 搜索 -->
    <t-form
      ref="form"
      :data="formData"
      label-width="calc(2em + 24px)"
      layout="inline"
      @submit="searchList"
    >
      <t-form-item label="片名" name="name">
        <t-input v-model="formData.name"></t-input>
      </t-form-item>
      <t-form-item label="主演" name="star">
        <t-input v-model="formData.star" ></t-input>
      </t-form-item>
      <t-form-item label="类型" name="type">
        <t-input v-model="formData.type" ></t-input>
      </t-form-item>
      <t-form-item label="地区" name="addr">
        <t-input v-model="formData.addr" ></t-input>
      </t-form-item>
      <t-form-item label-width="0">
        <t-space size="small">
          <t-button theme="primary" type="submit">查询</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
    <!-- 表格 -->
    <t-table
      style="margin-top: 15px;"
      row-key="id"
      :data="data"
      :columns="cols"
      :bordered="true"
      hover
      :pagination="pagination"
      show-header
      cell-empty-content="-"
      :loading="loading"
    >
      <template #title-slot-operation>
        <div style="display: flex; justify-content: space-between; align-items: center">
          操作
          <t-button size="small" @click="$router.push(`movieEdit`)" v-permiss="'新增电影'">新增</t-button>
        </div>
      </template>
      <template #cover = "{ row }">
        <img :src="row.cover" height="30" alt="" srcset="" style="display: inherit;" />
      </template>
      <template #operation="{ row }">
        <t-button variant="text" theme="warning" size="small" @click="$router.push(`movieEdit?id=${row.id}`)">
          <Edit2Icon v-permiss="'修改电影'" />
        </t-button>
        <t-popconfirm content="确认删除吗" @confirm="remove(row.id)">
          <t-button variant="text" theme="danger" size="small" v-permiss="'删除电影'"><DeleteIcon /></t-button>
        </t-popconfirm>
        <t-button variant="text" theme="warning" size="small" @click="openUpload(row)" v-permiss="'新增电影'"><CloudUploadIcon /></t-button>
      </template>
    </t-table>
    <!-- 文件上次弹窗 -->
    <t-dialog v-model:visible="visible" :cancelBtn="null" :confirmBtn="null" top="50" @close="reset">
      <t-form ref="form2">
        <t-form-item label="片名">
          <span>{{ videoInfo.name }}</span>
        </t-form-item>
        <t-form-item label="封面" name="cover">
          <t-upload
            ref="uploadRef1"
            v-model="file1"
            action="/api/upload"
            theme="image"
            accept="image/*"
            :data="avtarInfo"
            :auto-upload="false"
            :format-response="fileResponse"
            :locale="{
              triggerUploadText: {
                image: '请选择图片',
              },
            }"
            @selectChange="onAvtarChange"
            @fail="handleFail"
          ></t-upload>
        </t-form-item>
        <t-form-item label="影片" v-if="videoInfo.url">
          <video  width="300" autoplay="autoplay" muted="muted">
            <source :src="videoInfo.url" />
          </video>
        </t-form-item>
        <t-form-item label="影片文件" name="video">
          <t-upload
            ref="uploadRef2"
            v-model="video"
            action="/api/upload-demo"
            accept="video/*"
            :auto-upload="false"
            :locale="{
              triggerUploadText: {
                image: '请选择影片',
              },
            }"
            @selectChange="onSelectChange"
            @fail="handleFail"
          ></t-upload>
        </t-form-item>
        <t-form-item v-if="video.length">
          <t-progress style="width:200px" :percentage="progress" />
        </t-form-item>
        <t-form-item>
          <t-space size="15px">
            <t-button theme="success" @click="startUpload" >开始上传</t-button>
            <t-button theme="primary" @click="save" >保存修改</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue'
import { getMovieList, movieRemove, getMovieAreaList, getMovieTypeList, movieUpdate } from '@/api/movie'
import { MessagePlugin } from 'tdesign-vue-next'
import { Edit2Icon, DeleteIcon, CloudUploadIcon } from 'tdesign-icons-vue-next'
import { usePageOption } from '../../hook'
import { getCols } from './cols'
import { useUpload } from './upload'
const { pageOpt, pagination } = usePageOption(getList)
const form = ref(null)
const formData = reactive({
  name: '',
  star: '',
  type: '',
  addr: ''
}) // 搜索表单数据
// 获取列表数据
const loading = ref(false)
const data = ref([])
loading.value = true
// 获取电影列表
getList()
function getList () {
  getMovieList({ ...pageOpt, ...formData }).then(res => {
    pagination.total = res.total
    data.value = res.data
    loading.value = false
  })
}

// 表格头部和单元格配置
const cols = getCols()
cols.push({ colKey: 'operation', title: 'title-slot-operation', width: 130 })
// 删除
function remove (id) {
  movieRemove({ id }).then(res => {
    getList()
    MessagePlugin.success({
      content: '删除成功',
      duration: 2000
    })
  }).catch(err => {
    MessagePlugin.error(err.msg)
  })
}
// 获取地区列表
getMovieAreaList().then(res => {
  const area = cols.find(item => item.colKey === 'areaId')
  const areaList = reactive({})
  res.data.forEach(item => {
    areaList[item.id] = item.name
  })
  area.cell = (h, { row }) => {
    return areaList[row.areaId]
  }
})
// 获取类型列表
getMovieTypeList().then(res => {
  const type = cols.find(item => item.colKey === 'typeId')
  const typeList = reactive({})
  res.data.forEach(item => {
    typeList[item.id] = item.name
  })
  type.cell = (h, { row }) => {
    return typeList[row.typeId]
  }
})

const videoInfo = ref({})
const file1 = ref([])
function openUpload (row) {
  videoInfo.value = {}
  nextTick(() => {
    videoInfo.value = row
    visible.value = true
    if (videoInfo.value.cover) {
      file1.value[0] = {
        url: videoInfo.value.cover
      }
    }
  })
}

// 上传封面和影片的弹窗
const visible = ref(false)
const video = ref([])
const handleFail = ({ response }) => {
  console.log(response)
}
function fileResponse (response) {
  return {
    url: response.data.url
  }
}
const reset = () => {
  file1.value = []
  video.value = []
}
// 上传相关功能
const { onSelectChange, upload, progress, onAvtarChange, avtarInfo } = useUpload()
function startUpload () {
  upload().then(res => {
    console.log(res)
    videoInfo.value.url = ''
    nextTick(() => {
      videoInfo.value.url = res.url
    })
  })
}

function save () {
  console.log(file1.value, videoInfo.value)
  const cover = file1.value[0]?.url
  cover && (videoInfo.value.cover = cover)
  movieUpdate(videoInfo.value).then(res => {
    getList()
    visible.value = false
    MessagePlugin.success('修改成功')
  })
}

function searchList () {
  console.log(formData)
	pageOpt.page = 1
  getList()
}
</script>
<style scoped>
</style>
